<template>
	<view class="content">
		<view class="search-bar">
			<input class="search-input" placeholder="搜索新闻" @input="searchNews" />
		</view>
		<view v-if="loading" class="loading-container">
			<text class="loading-text">加载中...</text>
		</view>
		<view v-else class="uni-list">
			<view class="uni-list-cell card"
			      hover-class="uni-list-cell-hover" 
			      v-for="(item, index) in filteredNews" 
			      :key="index"
			      @tap="openinfo" :data-newsid="item.post_id">
				<view class="uni-media-list">
					<image class="uni-media-list-logo" :src="item.autor_avatar"></image>
					<view class="uni-media-list-body">
						<!-- 添加前缀文本到新闻标题前 -->
						<view class="uni-media-list-text-top">计工本2203张思琪202211000353读过 {{ item.title }}</view>
						<view class="uni-media-list-text-bottom">{{ formatDate(item.created_at) }}</view>
						<button class="favorite-btn" @tap.stop="toggleFavorite(item)">收藏</button>
					</view>
				</view>
			</view>
			<view v-if="loadingMore" class="loading-more">
				<text>加载更多...</text>
			</view>
		</view>
	</view>
</template>


<script>
export default {
	data() {
		return {
			news: [],
			filteredNews: [],
			favorites: uni.getStorageSync('favorites') || [],
			loading: true,
			loadingMore: false,
			page: 1
		};
	},
	onLoad() {
		this.fetchNews();
	},
	onPullDownRefresh() {
		this.page = 1;
		this.news = [];
		this.fetchNews(() => uni.stopPullDownRefresh());
	},
	onReachBottom() {
		if (!this.loadingMore) {
			this.page++;
			this.loadingMore = true;
			this.fetchNews(() => {
				this.loadingMore = false;
			});
		}
	},
	methods: {
		fetchNews(callback) {
			const cachedData = uni.getStorageSync('newsData');
			if (cachedData && this.page === 1) {
				this.news = cachedData;
				this.filteredNews = this.news;
			}

			uni.showLoading({ title: "加载中..." });
			uni.request({
				url: `https://unidemo.dcloud.net.cn/api/news?page=${this.page}`,
				method: 'GET',
				success: ({ data }) => {
					this.news = this.page === 1 ? data : this.news.concat(data);
					this.filteredNews = this.news;
					uni.setStorageSync('newsData', this.news);
					this.loading = false;
					if (callback) callback();
				},
				fail: () => {
					uni.showToast({ title: '加载失败，请重试', icon: 'none' });
					this.loading = false;
					if (callback) callback();
				},
				complete: () => uni.hideLoading()
			});
		},
		searchNews(event) {
			const query = event.detail.value.toLowerCase();
			this.filteredNews = this.news.filter(item => item.title.toLowerCase().includes(query));
		},
		toggleFavorite(item) {
			const index = this.favorites.findIndex(fav => fav.post_id === item.post_id);
			if (index > -1) {
				this.favorites.splice(index, 1);
				uni.showToast({ title: '已取消收藏', icon: 'none' });
			} else {
				this.favorites.push(item);
				uni.showToast({ title: '已收藏', icon: 'success' });
			}
			uni.setStorageSync('favorites', this.favorites);
		},
		formatDate(date) {
			const options = { year: 'numeric', month: 'short', day: 'numeric' };
			return new Date(date).toLocaleDateString('zh-CN', options);
		},
		openinfo(e) {
			const newsid = e.currentTarget.dataset.newsid;
			uni.navigateTo({ url: `../info/info?newsid=${newsid}` });
		}
	}
}
</script>

<style>
.content { padding: 10px; }
.loading-container, .loading-more { text-align: center; padding: 10px; }
.search-bar { padding: 10px; background-color: #f8f8f8; }
.search-input { width: 100%; padding: 8px; border-radius: 4px; border: 1px solid #ddd; }
.favorite-btn { margin-top: 5px; color: #ff9800; }
</style>
